import {getRequest} from './api'

//在初始化菜单
export const initMenu = (router, store) => {
  //首先判断store中的数据是否存在，如果存在，则说明这次跳转是正常的跳转，而不是用户按F5键或者直接在地址栏输入某个地址进入的，这时直接返回，不必执行菜单初始化
  if (store.state.routes.length > 0) {
    return;
  }

  //若store中不存在菜单数据，则需要初始化菜单数据。
  //通过getRequest("/config/sysMenu")方法获取菜单json数据后，通过formatRoutes方法将服务器返回的json数据转为router需要的格式，
  //这里主要是component，因为服务端返回的component是一个字符串，而router中需要的是一个组件，因此我们在formatRoutes方法中根据服务端返回的component动态加载需要的组件即可。
  //数据格式准备成功后，一方面将数据存到store中，一方面利用路由中的addRoutes方法将之动态加到路由中。
  getRequest("/config/sysMenu").then(resp => {
    if (resp && resp.status === 200) {
      let fmtRoutes = formatRoutes(resp.obj);
      router.addRoutes(fmtRoutes);
      store.commit('initMenu', fmtRoutes);
    }
  })
};

export const formatRoutes = (routes) => {
  let fmRoutes = [];
  routes.forEach(router => {
    let {
      id,
      path,
      name,
      component,
      requireAuth,
      keepAlive,
      iconCls,
      children
    } = router;
    if (children && children instanceof Array) {
      children = formatRoutes(children);
    }

    let fmRouter = {
      id: id,
      path: path,
      name: name,
      iconCls: iconCls,
      requireAuth: requireAuth,
      keepAlive: keepAlive,
      children: children,
      component(resolve) {
        if (component.startsWith("Home")) {
          require(['../views/' + component + '.vue'], resolve);
        } else if (component.startsWith("Emp")) {
          require(['../views/emp/' + component + '.vue'], resolve);
        } else if (component.startsWith("Per")) {
          require(['../views/personal/' + component + '.vue'], resolve);
        } else if (component.startsWith("Sal")) {
          require(['../views/salary/' + component + '.vue'], resolve);
        } else if (component.startsWith("Sta")) {
          require(['../views/statistics/' + component + '.vue'], resolve);
        } else if (component.startsWith("Sys")) {
          require(['../views/system/' + component + '.vue'], resolve);
        }
      }
    };
    fmRoutes.push(fmRouter);
  });
  return fmRoutes;
};
